package com.chen.palmar.project.init;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chen.palmar.R;
import com.chen.palmar.base.BaseFragment;
import com.chen.palmar.common.datasource.DataCenter;
import com.chen.palmar.common.override.HttpSubscriber;
import com.chen.palmar.common.widget.view.CircleImageView;
import com.chen.palmar.entity.UserInfoEntity;
import com.chen.palmar.project.set.AccountManagerActivity;
import com.chen.palmar.project.set.ApplyAgencyActivity;
import com.chen.palmar.project.set.ApplyIdentityActivity;
import com.chen.palmar.project.set.ApplyListActivity;
import com.chen.palmar.project.set.CollectionListActivity;
import com.chen.palmar.project.set.MessageManagerActivity;
import com.chen.palmar.project.set.SettingActivity;
import com.chen.palmar.project.set.ShopManagerActivity;
import com.chen.palmar.project.set.VipActivity;
import com.orhanobut.logger.Logger;
import com.primb.androidlibs.net.entity.MessageEvent;
import com.primb.androidlibs.net.exception.ApiException;
import com.squareup.picasso.Picasso;
import com.zhy.autolayout.AutoLinearLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.Bind;
import butterknife.OnClick;
import rx.Subscription;

/**
 * @author Chen
 * @date 2017/12/28
 * 功能描述：
 */

public class SetFragment extends BaseFragment {
    @Bind(R.id.iv_set_head)
    CircleImageView ivSetHead;
    @Bind(R.id.tv_user_name)
    TextView tvUserName;
    @Bind(R.id.iv_identity_state)
    ImageView ivIdentityState;
    @Bind(R.id.tv_identity_type)
    TextView tvIdentityType;
    @Bind(R.id.tv_account_state)
    TextView tvAccountState;
    @Bind(R.id.tv_account_manager)
    TextView tvAccountManager;
    @Bind(R.id.ly_shop)
    LinearLayout lyShop;
    @Bind(R.id.view_top)
    View viewTop;
    @Bind(R.id.swipe_set)
    SwipeRefreshLayout swipeSet;

    private UserInfoEntity.DataBean data;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //注册事件
        EventBus.getDefault().register(this);
        initData();
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_set;
    }

    @Override
    public void initData() {
        int statusBarHeight = -1;
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            //获取status_bar_height资源的ID
            int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
            if (resourceId > 0) {
                //根据资源ID获取响应的尺寸值
                statusBarHeight = getResources().getDimensionPixelSize(resourceId);
                Logger.v(statusBarHeight + "---");
                AutoLinearLayout.LayoutParams layoutParams = new AutoLinearLayout.LayoutParams(AutoLinearLayout.LayoutParams.MATCH_PARENT, statusBarHeight);
                viewTop.setLayoutParams(layoutParams);
            }
        }
        Picasso.with(getContext()).load(R.mipmap.set_head_icon).placeholder(R.mipmap.set_head_icon).error(R.mipmap.set_head_icon).fit().into(ivSetHead);
        getUserInfo();

        swipeSet.setOnRefreshListener(() -> {
            try {
                getUserInfo();
            } catch (Exception e) {
                e.printStackTrace();
                showToast("服务器数据格式异常");
                swipeSet.setRefreshing(false);
            }
        });
        swipeSet.setRefreshing(true);
        swipeSet.setColorSchemeColors(ContextCompat.getColor(getContext(), android.R.color.holo_blue_bright), ContextCompat.getColor(getContext(), android.R.color.holo_green_light), ContextCompat.getColor(getContext(), android.R.color.holo_orange_light), ContextCompat.getColor(getContext(), android.R.color.holo_red_light));

    }

    private void getUserInfo() {
        Subscription subscribe = DataCenter.getUserInfo().subscribe(new HttpSubscriber<UserInfoEntity>(getContext()) {

            @Override
            public void onNext(UserInfoEntity userInfoEntity) {
                swipeSet.setRefreshing(false);
                data = userInfoEntity.getData();
                if (TextUtils.isEmpty(data.getName())) {
                    tvUserName.setText(data.getUserId() + "");
                } else {
                    tvUserName.setText(data.getName());
                }
                tvIdentityType.setText(data.getType() == 1 ? "厂家" : "经销商");
                if (data.getType() != 1) {
                    tvAccountState.setVisibility(View.GONE);
                    lyShop.setVisibility(View.GONE);
                } else {
                    tvAccountState.setVisibility(View.VISIBLE);
                    lyShop.setVisibility(View.VISIBLE);
                    tvAccountState.setClickable(false);
                    if (data.getTypeStatus() == 1) {
                        ivIdentityState.setImageResource(R.mipmap.set_identity_yes);
                        tvAccountState.setVisibility(View.INVISIBLE);
                    } else if (data.getTypeStatus() == 2) {
                        tvAccountState.setVisibility(View.VISIBLE);
                        tvAccountState.setText("审核中");
                    } else if (data.getTypeStatus() == -1) {
                        tvAccountState.setText("禁用");
                    } else {
                        tvAccountState.setClickable(true);
                    }
                }
                Picasso.with(getContext()).load(data.getAvatar()).placeholder(R.mipmap.set_head_icon).error(R.mipmap.set_head_icon).fit().into(ivSetHead);
            }

            @Override
            public void onError(ApiException e) {
                super.onError(e);
                swipeSet.setRefreshing(false);
            }
        });
        subscription.add(subscribe);
    }

    @OnClick({R.id.tv_account_state, R.id.ly_info,R.id.tv_account_manager, R.id.ly_apply, R.id.ly_collect, R.id.ly_member, R.id.ly_message, R.id.ly_shop, R.id.ly_setting})
    public void onViewClicked(View view) {
        if (data == null) {
            showToast("数据加载失败，重试中");
            getUserInfo();
            return;
        }
        Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.tv_account_state:
                intent.setClass(getContext(), ApplyIdentityActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_account_manager:
                intent.setClass(getContext(), AccountManagerActivity.class);
                intent.putExtra("info", data);
                startActivity(intent);
                break;
            case R.id.ly_apply:
                intent.setClass(getContext(), ApplyListActivity.class);
                intent.putExtra("info", data);
                startActivity(intent);
                break;
            case R.id.ly_info:
                intent.setClass(getContext(), ApplyAgencyActivity.class);
                intent.putExtra("info", data);
                startActivity(intent);
                break;
            case R.id.ly_collect:
                intent.setClass(getContext(), CollectionListActivity.class);
                intent.putExtra("info", data);
                startActivity(intent);
                break;
            case R.id.ly_member:
                intent.setClass(getContext(), VipActivity.class);
                intent.putExtra("info", data);
                startActivity(intent);
                break;
            case R.id.ly_message:
                intent.setClass(getContext(), MessageManagerActivity.class);
                intent.putExtra("info", data);
                startActivity(intent);
                break;
            case R.id.ly_shop:
                if (data.getTypeStatus() == 1) {
                    intent.setClass(getContext(), ShopManagerActivity.class);
                    intent.putExtra("info", data);
                    startActivity(intent);
                } else if (data.getTypeStatus() == 2) {
                    showToast("身份审核中");
                } else if (data.getTypeStatus() == -1) {
                    showToast("当前身份禁用");
                } else {
                    intent.setClass(getContext(), ApplyIdentityActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.ly_setting:
                intent.setClass(getContext(), SettingActivity.class);
                intent.putExtra("info", data);
                startActivity(intent);
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MessageEvent messageEvent) {
        switch (messageEvent.getEventType()) {
            case AccountManagerActivity.EVENT_ACCOUNT_CODE:
                getUserInfo();
                break;
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        //取消注册事件
        EventBus.getDefault().unregister(this);
    }
}
